﻿namespace EFS.Common.UI.Controls
{
	public class DataGridDoubleClickBehavior : System.Windows.Interactivity.Behavior<System.Windows.Controls.DataGrid>
	{
		private readonly EFS.Common.MouseClickManager _gridClickManager;
		public event System.EventHandler<System.Windows.Input.MouseButtonEventArgs> DoubleClick;

		public DataGridDoubleClickBehavior()
		{
			_gridClickManager = new EFS.Common.MouseClickManager(300);
			_gridClickManager.DoubleClick += new System.Windows.Input.MouseButtonEventHandler(_gridClickManager_DoubleClick);
		}

		protected override void OnAttached()
		{
			base.OnAttached();

			AssociatedObject.LoadingRow += OnLoadingRow;
			AssociatedObject.UnloadingRow += OnUnloadingRow;
		}

		private void OnUnloadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e)
		{
			//row is no longer visible so remove double click event otherwise
			//row events will miss fire
			e.Row.MouseLeftButtonUp -= _gridClickManager.HandleClick;
		}

		private void OnLoadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e)
		{
			//row is visible in grid, wire up double click event
			e.Row.MouseLeftButtonUp += _gridClickManager.HandleClick;
		}

		protected override void OnDetaching()
		{
			base.OnDetaching();

			AssociatedObject.LoadingRow -= OnLoadingRow;
			AssociatedObject.UnloadingRow -= OnUnloadingRow;
		}

		private void _gridClickManager_DoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			if (DoubleClick != null)
			{
				DoubleClick(sender, e);
			}
		}
	}

}